import Anchor from './anchor'

export default class Node {
  constructor(options = {}) {
    this.id = options.id || `node-${Date.now()}`
    this.x = options.x || 0
    this.y = options.y || 0
    this.width = options.width || 80
    this.height = options.height || 40
    this.label = options.label
    this.type = options.type || 'default'
    this.color = options.color || '#f0f0f0'
    this.selected = false
    this.anchors = []

    // 初始化锚点
    if (options.anchors) {
      options.anchors.forEach(anchor => {
        if (!(anchor instanceof Anchor)) {
          anchor = new Anchor({...anchor, nodeId: this.id})
        }
        this.anchors.push(anchor)
      })
    } else {
      // 默认添加四个锚点（上下左右）
      this.anchors = [
        new Anchor({ id: `anchor-${this.id}-1`, x: 0, y: this.height / 2, nodeId: this.id }),
        new Anchor({ id: `anchor-${this.id}-2`, x: this.width / 2, y: 0, nodeId: this.id }),
        new Anchor({ id: `anchor-${this.id}-3`, x: this.width, y: this.height / 2, nodeId: this.id }),
        new Anchor({ id: `anchor-${this.id}-4`, x: this.width / 2, y: this.height, nodeId: this.id })
      ]
    }
  }

  // 获取锚点
  getAnchor(anchorId) {
    return this.anchors.find(anchor => anchor.id === anchorId)
  }

  // 转换为JSON
  toJSON() {
    return {
      id: this.id,
      x: this.x,
      y: this.y,
      width: this.width,
      height: this.height,
      label: this.label,
      type: this.type,
      color: this.color,
      anchors: this.anchors.map(anchor => anchor.toJSON())
    }
  }
}